<template>
  <div>
    <!-- 查询参数及按钮部分 -->
    <div class="filter-container">
      <el-dialog  v-dialogDrag  
        :close-on-click-modal="false"
        :title="dialogStatus"
        :visible.sync="dialogEditFormVisible"
        style="padding: 0px"
        width="60%"
      >
        <el-form
          ref="dataForm"
          class="dialog-Backgroundcolor"
          :model="listQuery"
          label-position="right"
          label-width="120px"
        >
          <el-row>
            <el-row style="margin-left: -30px">
              <!-- <el-col :span="8">
                <el-form-item label="人员类别：">
                  <el-select v-model="formData.state" class="filter-item" placeholder="--请选择--" style="width:100%" >
                    <el-option label="全部人员" value="" />
                    <el-option label="在职人员" value="3" />
                    <el-option label="离休人员" value="1" />
                  </el-select>
                </el-form-item>
              </el-col> -->
              <el-col :span="8">
                <el-form-item label="身份证号码：">
                  <el-input v-model="formData.idenNo" style="width:100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="姓名：">
                  <el-input v-model="formData.personName" style="width:100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row style="margin-left: -30px">
              <!-- <el-col :span="10"> -->
              <el-form-item label="工资项：">
                  <el-select v-model="formData.salaryColum" class="filter-item" placeholder="--请选择--" clearable>
                    <el-option v-for="item in salaryNames" :key="item.value" :label="item.key" :value="item.value" />
                  </el-select>&nbsp;
                  <el-input-number v-model="formData.salaryColumMin"  :controls="false"  class="filter-item"/>~
                  <el-input-number v-model="formData.salaryColumMax"  :controls="false"  class="filter-item" />
                </el-form-item>
                            
              <!-- </el-col> -->
            </el-row>
            <el-button type="primary" style="float:right;" @click="handleFilter">
              查询
            </el-button>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
    <el-row>
      <el-col :span="4">
        <el-select
          v-model="formData.salaryType"
          class="filter-item"
          placeholder="工资类型"
          @change="handleFilter"
        >
          <el-option label="全部工资类型" value="" />
           <el-option
                        v-for="item in salaryTypes"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                      />
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-select 
        v-model="formData.state" 
        class="filter-item" 
        placeholder="人员类型" 
        style="width:100%"  
        @change="handleFilter" >
          <el-option label="全部人员类型" value="" />
          <el-option label="在职人员" value="3" />
          <el-option label="离退休人员" value="1" />
        </el-select>
      </el-col>
    </el-row>
    <el-row style="margin-top: 10px">
      <el-col :span="24">
        <div>单位名称：{{ unitName }}</div>
        <span style="font-size:16px">实发合计：{{ Number(reallySendSalarySum).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") }}元</span>
        <span style="font-size:16px">（其中：在职合计：{{ Number(workSalarySum).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") }}元</span>，
        <span style="font-size:16px">离退休合计：{{ Number(retireSalarySum).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") }}元）</span><br>
        <span style="font-size:16px">在编人员：{{ personTotal }}人</span>
        <span style="font-size:16px">（其中：在职：{{ workTotal }}人</span>，
        <span style="font-size:16px">离退休：{{ retireTotal }}人）</span>；
        <span style="font-size:16px">单位减员：{{ unitMinusTotal }}人</span>
        <span style="font-size:16px">（其中：在职：{{ workMinusTotal }}人</span>，
        <span style="font-size:16px">离退休：{{ retireMinusTotal }}人）</span>；
        <span style="font-size:16px">单位增员：{{ unitPlusTotal }}人</span>
        <span style="font-size:16px">（其中：在职：{{ workPlusTotal }}人</span>，
        <span style="font-size:16px">离退休：{{ retirePlusTotal }}人）</span>
      </el-col>
      <!-- <el-col v-if="this.tabPane === '-1'" :span="1">
        <el-link type="primary" @click="openAuditExplain">
          <span>退回说明</span>
        </el-link>
      </el-col> -->
    </el-row>
    <!-- 表格部分 -->
    <vxe-table
      ref="singalTable"
      v-loading="listLoading"
      border="inner"
      resizable
      :data="list"
      show-overflow
      show-header-overflow
      show-footer-overflow
      show-footer
      :footer-method="footerMethod"
      :scroll-y="{gt: 20}"
      :sort-config="{trigger: 'cell', orders: ['desc', 'asc', null]}"
      fit
      row-id="id"
      :tree-config="{transform: true}"
      :height="tableHeight"
      class="my-test"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
    >
      <template slot="empty">
        <tableEmpty />
      </template>
      <vxe-table-column lable="" tree-node field="index" min-width="80" fixed="left" />
      <vxe-table-column label="" min-width="50" fixed="left">
        <template v-slot:header>
          <vxe-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAll" />
        </template>
        <template v-slot="scope">
          <vxe-checkbox v-if="scope.row.index && scope.row.index !== '合计'" v-model="scope.row.check" @change="handleCheck" />
        </template>
      </vxe-table-column>
      <vxe-table-column width="30" fixed="left">
        <template slot-scope="{row}">
          <i v-if="row.existsFile === 1" class="el-icon-paperclip file-logo" />
        </template>
      </vxe-table-column>
      <!-- <vxe-table-column title="工资月份" min-width="80" fixed="left">
        <template slot-scope="{row}">
          <span :style="{ color: row.different === 1 ? 'red':'black' }">{{ row.currentMonth }}</span>
        </template>
      </vxe-table-column>
      <vxe-table-column title="科室" min-width="100" fixed="left">
        <template slot-scope="{row}">
          <span :style="{ color: row.different === 1 ? 'red':'black' }">{{ row.deptId | deptNameFilter(that) }}</span>
        </template>
      </vxe-table-column> -->
      <vxe-table-column title="姓名" min-width="100" fixed="left" field="personName" sortable >
        <template slot-scope="{ row }">
          <el-link type="primary" @click="viewInfo(row)">
            <span :style="{ color: row.different === 1 ? 'red':'black' }">{{ row.personName }}</span>
          </el-link>
        </template>
      </vxe-table-column>
      <vxe-table-column title="身份证号" min-width="200" fixed="left"  field="idenNo" sortable >
        <template slot-scope="{row}">
          <span :style="{ color: row.different === 1 ? 'red':'black' }">{{ row.idenNo  }}</span>
        </template>
      </vxe-table-column>
      
      <vxe-table-column v-for="item in columnNamePersonTypes" :field="item.columnName.split('_')[0]"  :key="item.columnName" :title="item.columnName.split('_')[0] | salaryNameFilter(that)" align="right" min-width="150">
        <template slot-scope="{ row }">
          <!--判断当前行是否处于编辑状态，并且判断该字段是否是计算值-->
          <div :style="{ float: 'right', color: (row[item.columnName.split('_')[0]] !== row[item.columnName.split('_')[0] + '_history'] || (row.s1 === 0 && row.s1_history === 0)) && row.index !== '合计' ? 'red' : 'black' }">
            <vxe-input
              v-if="row.isOperate && item.columnName.split('_')[1] !== 'compute' && item.personTypeCode.split(',').includes(row.meritPayCode)"
              v-model="row['input' + item.columnName.split('_')[0]]"
              placeholder=""
              type="float"
              align="right"
              min="0"
              max="99999999"
              clearable
              @keyup.enter.native="nextInput($event)"
            />
            <span v-if="row.isOperate && item.columnName.split('_')[1] === 'compute' ">{{ Number(row['input' + item.columnName.split('_')[0]]).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") }}</span>
            <!--获取不带后缀的字段名-->
            <span v-if="!row.isOperate">{{ Number(row[item.columnName.split('_')[0]]).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") }}</span>
          </div>
        </template>
      </vxe-table-column>
    </vxe-table>
    <el-dialog  v-dialogDrag  
      :close-on-click-modal="false"
      title="导入"
      :visible.sync="dialogImportFormVisible"
      width="29%"
    >
      <el-upload
        class="upload-demo"
        drag
        style="padding-left: 2px"
        action="#"
        list-type="multipart/form-data"
        accept=".xls,.xlsx"
        :show-file-list="false"
        :http-request="uploadExcel"
        v-if="!importLoading"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip" />
      </el-upload>
      <span v-if="importLoading">正在处理，请稍等...</span>
    </el-dialog>
    <el-dialog  v-dialogDrag  
      title="退回说明"
      :visible.sync="auditFormVisible"
      width="30%"
      max-height="500px"
    >
      <el-form
        ref="auditForm"
        :model="auditFormData"
        label-position="right"
        label-width="120px"
        size="small"
      >
        <el-row>
          <el-col>
            <el-input
              v-model="auditFormData.auditExplain"
              type="textarea"
              :rows="4"
              maxlength="500"
            />
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      title="请选择单位"
      :visible.sync="dialogVerifyFormVisible"
      style="padding: 0px"
      width="50%"
    >    
     <el-row>
       <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px; float: right"
            type="primary"
             
            @click="dialogVerifyFormVisible = false"         
          >
            取消
          </el-button> 
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px; float: right"
            type="primary"
            
             @click="submitAll"
             
          >
            提交
          </el-button>
        </el-row>
          <el-tree
            ref="tree"
            :data="agencyTreeData"
            show-checkbox                  
            node-key="id"                  
            :props="defaultProp"
              >                   
          </el-tree>                 
    </el-dialog>

    <pagination
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <Enclosure ref="enc" :middle-table-code="2" />
    <UnitSalaryReportChildrenEditAll
      v-if="handleEditAllShow"
      :dept-names="deptNames"
      :column-names="columnNames"
      :select-data="checkList"
      :salary-names="salaryNames"
      :compute-formula="computeFormula"
      :columnNamePersonTypes="columnNamePersonTypes"
      @close="editAllClose"
    />
    <PersonSalaryInfo ref="personSalaryInfo" />
    <ApprovalProcess ref="app" />
       <uploadLoadBatchAuditOne v-if="upload_load" ref="uploadLoadBatchAuditOne" :agencyVerList="agencyVerList" :menuid="this.menuid" @close="uploadClose"/>
       <uploadLoadImport v-if="uploadLoadImportVisible" ref="uploadLoadImport" :guid="this.importGuid" :Executing="this.Executing" @close="uploadLoadImportVisibleClose"/>
  </div>
</template>
<script>
import {
  querySalaryNameDict,
  generateFormula,
  queryReallySendSalarySumAndPersonTotal,
  queryColumnName,
  queryColumnNamePersonType,
  queryUnitSalaryReportPage,
  submitData,
  submitOne,
  rejectSubmitOne,
  rejectEdit,
  outPutSalaryReportList,
  ImportAsync,
  verfityExistNoFilePerson,
  JudgePersonBank
} from '@/api/unitSalaryReport/unitSalaryReport'
import { getSalaryType,
  getConfigCtrlByTypeMof} from '@/api/baseInfo'
import { queryAgencyNameAndState } from '@/api/unitInformationMaintenance/unitInformationEdit'
import { getDepartmentList } from '@/api/unitInformationMaintenance/internalOrganizationMaintenance'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import tableEmpty from '@/components/table/empty'
import Enclosure from '@/components/Enclosure'
import PersonSalaryInfo from '@/components/personSalaryInfo/personSalaryInfo'
import { getAgencyVerifyByAgencyId, getPaidWagesCount, getUnreviewedPersonCount } from '@/api/agencyVerify'
import { queryPersonFileNum } from '@/api/personInfoMaintenance/personChangeEdit'
import ApprovalProcess from '@/components/ApprovalProcess/ApprovalProcess'
import UnitSalaryReportChildrenEditAll from './unitSalaryReportChildrenEditAll'
import { getAuthAgencyTrees } from '@/api/baseInfo';
import uploadLoadBatchAuditOne from './uploadLoadBatchAuditOne';
import uploadLoadImport from './uploadLoadImport';
export default {
  name: 'UnitSalaryReportChildren',
  components: { ApprovalProcess, Pagination, tableEmpty, Enclosure, PersonSalaryInfo, UnitSalaryReportChildrenEditAll, uploadLoadBatchAuditOne,
    uploadLoadImport },
  filters: {
    deptNameFilter(value, that) {
      const deptNames = that.deptNames
      for (const item of deptNames) {
        if (value === item.code) {
          return item.name
        }
      }
    },
    //号码脱敏显示
    hideMiddle(val) {
      if(val !== undefined&& val !== null){//避免列表中存在空数据报错
        return `${val.substring(0,4)}****${val.substring(val.length-4)}`
      }else{
        return val
      }
    },
    // 工资项滤器
    salaryNameFilter(value, that) {
      const salaryNames = that.salaryNames
      for (const item of salaryNames) {
        if (item.value === value) {
          return item.key
        }
      }
    }
  },
  props: ['tabPane', 'treeData'],
  data() {
    return {
      number: 1,
      tableHeight: null,
      dialogStatus: '',
      dialogEditFormVisible: false,
      dialogImportFormVisible: false,
      uploadLoadImportVisible: false,
      importGuid:'',
      Executing:'',
      importLoading: false,
      formStatus: '',
      configCtrl:'1',
      that: this,
      reallySendSalarySum: '0.00',
      workSalarySum: '0.00',
      retireSalarySum: '0.00',
      personTotal: '0',
      workTotal: '0',
      retireTotal: '0',
      unitMinusTotal: '0',
      unitPlusTotal: '0',
      retireMinusTotal: '0',
      workMinusTotal: '0',
      retirePlusTotal: '0',
      workPlusTotal: '0',
      openenclosure: true,
      list: [],
      submitList: [],
      submitPersonIds: [],
      salaryTypes:[],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 200,
        flag: 'all',
        menuid: this.$router.currentRoute.meta.menuid
      },
      formData: {
        state: '', // 人员类别
        idenNo: '', // 身份证号码
        personName: '', // 姓名
        salaryType: '',//人员类型
        salaryColum:'',
        salaryColumMin:'',
        salaryColumMax:''
      },
      columnNames: [], // 动态表头
      allColumnNames: ['s1','s2','s3','s4','s5','s6','s7','s8','s9','s10','s11','s12','s13','s14','s15','s16','s17','s18','s19','s20','s21','s22','s23','s24','s25','s26','s27','s28','s29','s30','s31','s32','s33','s34','s35','s36','s37','s38','s39','s40','s41','s42','s43','s44','s45','s46','s47','s48','s49','s50','s51','s52','s53','s54','s55','s56','s57','s58','s59','s60','s61','s62','s63','s64','s65','s66','s67','s68','s69','s70','s71','s72','s73','s74','s75','s76','s77','s78','s79','s80','s81','s82','s83','s84','s85','s86','s87','s88','s89','s90','s91','s92','s93','s94','s95','s96','s97','s98','s99','s100'], // 所有工资项
      columnNamePersonTypes: [], // 动态表头带工资类型信息
      salaryNames: [],
      deptNames: [],
      unitName: '预算单位',
      agencyName: '',
      agencyId: null,
      menuid: this.$router.currentRoute.meta.menuid,
      isSubmitInAgency: 0,
      salaryVerifiedInAgencyCode: '0',
      checkAll: false,
      indeterminate: false,
      checkList: [],
      changeList: {},
      inputList: {}, // 缓存最后一次输入正确的值，id{id}_inputs1 大括号内的id恢替换成id的数值
      computeFormula: [],
      auditFormVisible: false,
      auditFormData: {
        auditExplain: ''
      },
      handleEditAllShow: false,
      defaultProp: {
        id: "id",
        children: "children",
        label: "label",
      },
      dialogVerifyFormVisible: false,
      agencyTreeData: [],
      agencyVerList: [],
      upload_load:false,
      isEdit: false
    }
  },
  watch: {
    submitList: {
      immediate: true,
      deep: true,
      handler(val) {
        this.calculate(val)
      }
    },
    // 表格的数据数组
    // list(val) {
    //   this.doLayout()
    // },
    treeData(val) {
      if (val && val.isleaf === '1') {
        this.unitName = val.label.split('-')[1]
        this.agencyId = val.id
        this.handleTree(val)
      }
    }
  },
  mounted() {
    this.getTbHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },
  created() {
    this.listQuery.flag = this.tabPane
    if (this.treeData && this.treeData.isleaf === '1') {
      this.unitName = this.treeData.label.split('-')[1]
      this.agencyId = this.treeData.id
      this.initDict()
      this.queryAgencyNameAndState()
      this.handleFilter()
      this.getAgencyVerifyByAgencyId()
    }
  },
  methods: {
    editAllClose($event) {
      this.handleEditAllShow = false
      if ($event === 2) {
        this.handleFilter()
      }
    },
    processnode() {
      this.$refs.app.getList(this.agencyId)
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 350
    },
    /* 重新渲染table组件 */
    // doLayout() {
    //   this.$nextTick(() => {
    //     this.$refs.singalTable.doLayout()
    //   })
    // },
    // 获取审核意见
    getAgencyVerifyByAgencyId() {
      getAgencyVerifyByAgencyId(this.listQuery.agencyId).then((response) => {
        this.auditFormData.auditExplain = response.data.auditExplain
      })
    },
    // 打开审核意见
    openAuditExplain() {
      this.auditFormVisible = true
    },
    // 查询
    query() {
      this.dialogStatus = '查询'
      this.dialogEditFormVisible = true
    },
    calculate(submitList) {
      // 获取每一行的数据进行计算
      for (const submit of submitList) {
        const columnList=[]
        for(const columnObject of this.columnNamePersonTypes){
            if(columnObject.personTypeCode.split(",").includes(submit.meritPayCode)){
              columnList.push(columnObject.columnName.split("_")[0])
            }
        }
        for (const computeFormula of this.computeFormula) {
          const meritPayCode = computeFormula.meritPayCode.split(',')
          if (meritPayCode.includes(submit.meritPayCode)) {
            const formula = computeFormula.computeFormula
            const decimalPlace = computeFormula.decimalPlace
            const equation = formula.split('=')
            const answer = equation[0]
            const args = equation[1].split(',')
            let calc = ''
            for (let arg of args) {
              if (arg.startsWith('&') && arg.endsWith('&')) {
                arg = arg.substring(1, arg.length - 1)
                if (arg !== 'null') {
                  if(columnList.includes(arg)){
                    calc += submit['input' + arg] === ''| submit['input' + arg] === undefined ? '0' : submit['input' + arg]
                  }else{
                      calc += 0;
                  }
                } else {
                  calc += 0
                }
              } else {
                calc += arg
              }
            }
            submit['input' + answer] = Number(this.$math.round(this.$math.evaluate(calc), decimalPlace))
          }
        }
      }
    },
    querySalaryNameDict(){
      Object.assign(this.listQuery, this.formData)
      this.listQuery['agencyId'] = this.agencyId
       // 查询工资项名称
      querySalaryNameDict(this.listQuery)
        .then(res => {
          this.salaryNames = res.data
        })
        .catch(() => {
          this.salaryNames = []
        })
    },
    
    // 初始化字典
    initDict() {
      //获取工资类型
       getSalaryType().then(response => {
        this.salaryTypes = Object.assign({}, response.data)
      })
      // 查询工资项名称
      querySalaryNameDict(this.listQuery)
        .then(res => {
          this.salaryNames = res.data
        })
        .catch(() => {
          this.salaryNames = []
        })
      // 查询部门名称
      getDepartmentList({ agencyId: this.agencyId })
        .then(res => {
          this.deptNames = res.data
        })
        .catch(() => {
          this.deptNames = []
        })
      // 生成计算公式
      generateFormula(this.agencyId)
        .then(res => {
          this.computeFormula = res.data
        })
        .catch(() => {
          this.computeFormula = []
        })
        //获取是否上传附件做校验
         getConfigCtrlByTypeMof("fileVerify").then(response => {
        this.configCtrl = response.data
        
        
      })
    },

    queryAgencyNameAndState() {
      // 查询机构名称
      return queryAgencyNameAndState(this.agencyId).then(res => {
        this.agencyName = res.data.agencyName
        this.isSubmitInAgency = res.data.isSubmitInAgency
        this.salaryVerifiedInAgencyCode = res.data.salaryVerifiedInAgencyCode
      }).catch(() => {
        this.agencyName = ''
        this.isSubmitInAgency = 0
        this.salaryVerifiedInAgencyCode = '0'
      })
    },

    queryReallySendSalarySumAndPersonTotal() {
      queryReallySendSalarySumAndPersonTotal(this.agencyId, 0).then(res => {
        this.reallySendSalarySum = res.data.reallySendSalarySum
        this.workSalarySum = res.data.workSalarySum
        this.retireSalarySum = res.data.retireSalarySum
        this.personTotal = res.data.personTotal
        this.workTotal = res.data.workTotal
        this.retireTotal = res.data.retireTotal
        this.unitMinusTotal = res.data.unitMinusTotal
        this.unitPlusTotal = res.data.unitPlusTotal
        this.retireMinusTotal = res.data.retireMinusTotal
        this.workMinusTotal = res.data.workMinusTotal
        this.retirePlusTotal = res.data.retirePlusTotal
        this.workPlusTotal = res.data.workPlusTotal
      }).catch(() => {
        this.reallySendSalarySum = '0.00'
        this.workSalarySum = '0.00'
        this.retireSalarySum = '0.00'
        this.personTotal = '0'
        this.workTotal = '0'
        this.retireTotal = '0'
        this.unitMinusTotal = '0'
        this.unitPlusTotal = '0'
        this.retireMinusTotal = '0'
        this.workMinusTotal = '0'
        this.retirePlusTotal = '0'
        this.workPlusTotal = '0'
      })
    },

    // 动态获取表头
    getColumnNames() {
      Object.assign(this.listQuery, this.formData)
      this.listQuery['agencyId'] = this.agencyId
      queryColumnName(this.listQuery)
        .then(response => {
          this.columnNames = response.data
        })
        .catch(() => {
          this.columnNames = []
        })
    },
    //动态表头带人员工资类型信息
    queryColumnNamePersonType(){
      this.columnNamePersonTypes=[]
      Object.assign(this.listQuery, this.formData);
      this.listQuery["agencyId"] = this.agencyId;
      queryColumnNamePersonType(this.listQuery)
        .then((response) => {
          this.$forceUpdate()
          this.columnNamePersonTypes=response.data
        })
        .catch(() => {
          this.columnNamePersonTypes = [];
        });
    },
    handleTree(data) {
      this.initDict()
      this.queryAgencyNameAndState()
      this.handleFilter()
      this.getAgencyVerifyByAgencyId()
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1
      // this.listQuery.limit = 10
      this.getList()
      this.dialogEditFormVisible = false
    },

    initData() {
      this.checkAll = false
      this.indeterminate = false
      this.listLoading = false
      this.submitList = []
      this.submitPersonIds = []
      this.checkList = []
      this.inputList = {}
    },

    // 获取数据
    getList() {
      this.listLoading = true
      this.isEdit = false
      this.getColumnNames()
      this.queryColumnNamePersonType()
      this.getTreeData()
      this.queryReallySendSalarySumAndPersonTotal()
      Object.assign(this.listQuery, this.formData)
      this.listQuery['agencyId'] = this.agencyId
      queryUnitSalaryReportPage(this.listQuery)
        .then(response => {
          this.list = response.data.rows
          for (const item of this.list) {
            if (item.children) {
              // table中的row-key需要id不为空且不可重复
              item.children[0].personId += 'noRepeat'
            }
            this.$set(item, 'check', false)
          }
          this.total = response.data.total
          this.initData()
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.initData()
        })
    },
    // 批量修改
    handleEditAll() {
      if (this.checkList.length === 0) {
        this.$message({
          message: '请选择数据',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        return
      }
      this.handleEditAllShow = true
    },
    // 编报，修改
    handleEdit() {
      this.queryAgencyNameAndState().then(() => {
        // 送审后不可编辑
        if (this.isSubmitInAgency === 1) {
          this.$message({
            message: '当前单位数据已送审，不可编辑！',
            type: 'warning',
            showClose: true,
            duration: 4000
          })
          return
        }
        this.isEdit = true
        const selection = this.checkList
        if (selection.length === 0) {
          this.$message({
            message: '请选择数据',
            type: 'warning',
            showClose: true,
            duration: 4000
          })
          return
        }
        for (let name of this.columnNames) {
          name = name.split('_')[0]
          for (const item of selection) {
            let value = ''
            if (item[name] !== 0) {
              value = item[name]
            }
            this.$set(item, 'input' + name, value)
          }
        }
        for (const item of selection) {
          if (!this.submitPersonIds.includes(item.personId)) {
            this.$set(item, 'isOperate', true)
            this.$set(item, 'columnNames', this.columnNames.join(','))
            this.submitPersonIds.push(item.personId)
            this.submitList.push(item)
          }
        }
        this.calculate(this.submitList)
      })
    },
    // 取消修改
    handleCancelEdit() {
      const selection = this.checkList
      if (selection.length === 0) {
        this.$message({
          message: '请选择数据',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        return
      }
      const submitPersonIds = this.submitPersonIds
      const submitList = this.submitList
      for (const item of selection) {
        this.$set(item, 'isOperate', false)
        for (let i = 0; i < submitPersonIds.length; i++) {
          if (item.personId === submitPersonIds[i]) {
            submitPersonIds.splice(i, 1)
            i--
            break
          }
        }
        for (let j = 0; j < submitList.length; j++) {
          if (item === submitList[j]) {
            submitList.splice(j, 1)
            j--
            break
          }
        }
      }
    },
    // 保存
    handleSave() {
      const submitList = this.submitList
      if (submitList.length === 0) {
        this.$message({
          message: '没有可保存的数据',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        this.$emit('handleSaveBtnLoading')
        return
      }
      const personIds = []
      for (const submit of submitList) {
        personIds.push(submit.personId)
      }
      // 校验附件
      const params = {}
      params['personId'] = personIds.join(',')
      params['agencyId'] = this.agencyId
      params['operateType'] = '2'
      queryPersonFileNum(params).then(response => {
        for (const submit of submitList) {
             const columnList=[]
            for(const columnObject of this.columnNamePersonTypes){
              if(columnObject.personTypeCode.split(",").includes(submit.meritPayCode)){
                columnList.push(columnObject.columnName.split("_")[0])
              }
            }
            for (let name of this.allColumnNames) {
              if(columnList.includes(name)){  
                  submit[name] = submit["input" + name];
              }else{
                submit[name] = 0
              }              
            }
          }

        submitData(submitList).then(() => {
          if (response.data === 0) {
            this.$message({
              showClose: true,
              message: '保存成功！',
              type: 'success',
              duration: 4000
              // onClose: this.appendixOpen //如果存在未上传附件的人员，则打开附件管理让其上传附件
            })
          } else {
            this.$message({
              message: '保存成功',
              type: 'success',
              showClose: true,
              duration: 4000
            })
          }
          this.getList()
          this.$emit('handleSaveBtnLoading')
        }).catch(() => {
          this.$emit('handleSaveBtnLoading')
        })
      }).catch(() => {
        this.$emit('handleSaveBtnLoading')
      })
      // }).catch(() => {
      //   this.$emit('handleSaveBtnLoading')
      // })
    },

    // 撤销修改
    handleRejectEdit() {
      const selection = this.checkList
      if (selection.length !== 1) {
        this.$message({
          message: '请选择一条数据',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        this.$emit('handleRejectEditBtnLoading')
        return
      }
      // this.$confirm('确定撤销修改吗？', '提示', {
      //   closeOnClickModal: false,
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      rejectEdit(selection[0])
        .then(res => {
          this.$message({
            message: '撤销修改成功',
            type: 'success',
            showClose: true,
            duration: 4000
          })
          this.getList()
          this.$emit('handleRejectEditBtnLoading')
        })
        .catch(() => {
          this.$emit('handleRejectEditBtnLoading')
        })
        // })
        // .catch(() => {
        //   this.$emit('handleRejectEditBtnLoading')
        // })
    },
    //获取未审核单位树
    getTreeData() {
      this.count = 0;
      getAuthAgencyTrees(this.listQuery).then(response => {
        this.agencyTreeData = response.data;
      })
    },

    //显示批量送审弹窗
    handleSubmitAll(){
      this.dialogVerifyFormVisible = true
    },
    submitAll() { 
      this.dialogVerifyFormVisible = false
      // this.$emit("trueSubmitBtnLoadings");
      const selections = this.$refs.tree.getCheckedKeys(true);
       if (selections.length == 0) {
        this.$message({
          message: "没有可送审的数据",
          type: "warning",
          showClose: true,
          duration: 4000,
        });
        this.$emit("handleSubmitBtnLoadings");
        return;
      }

        this.agencyVerList = [],
        selections.forEach(item => {
        const current = {}
        current['agencyId'] = item
        this.agencyVerList.push(current)
      })
        this.$msgbox({
          title: '是否确认',
          // dangerouslyUseHTMLString: true,
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {            
            if (action === 'confirm') {
              done();
              this.upload_load = true            
              // this.makeSalaryData() // 进度条同时，调用接口
            } else {
              done();
              instance.confirmButtonLoading = false;
              this.uploadClose()
              // done();
            }
          }
        }).then(action => {
           done();
          this.$message({
            type: 'info',
            message: 'error: ' + action
          });
        });
       //this.$emit("handleSubmitBtnLoadings");

    },
    uploadClose() {
      this.upload_load = false
       this.$emit('handleSubmitBtnLoadings')
      // this.listQuery.agencySelected=''//批量生成完后清空选择值，再调查询方法，否则会报414
      // this.getMessage()
       this.handleFilter()
    },
    uploadLoadImportVisibleClose() {
      this.uploadLoadImportVisible = false
      this.getList()
    },
    // 送审
    handleSubmit() {
      if (this.total === 0) {
        this.$message({
          message: '没有可送审的数据',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        this.$emit('handleSubmitBtnLoading')
        return
      }
      if(this.isEdit){
        this.$message({
          message: "存在修改数据待保存！请先保存数据！",
          type: "warning",
          showClose: true,
          duration: 4000,
        });
        this.$emit("handleSubmitBtnLoading");
        return;
      }
      getPaidWagesCount(this.agencyId).then(count => {
        if (count !== 0) {
          this.$message({
            message: '有应发工资为0或实发工资小于0人员',
            type: 'warning',
            showClose: true,
            duration: 4000
          })
          this.$emit('handleSubmitBtnLoading')
          return
        }
        getUnreviewedPersonCount(this.agencyId).then(count1 => {
          if (count1 !== 0) {
            this.$message({
              message: '有未经审核人员',
              type: 'warning',
              showClose: true,
              duration: 4000
            })
            this.$emit('handleSubmitBtnLoading')
            return
          }
          verfityExistNoFilePerson(this.agencyId).then(res => {
            if (res.data&&this.configCtrl=='1') {
              this.$message({
                showClose: true,
                message: '存在未上传附件的人员',
                type: 'warning',
                duration: 4000
              })
              this.$emit('handleSubmitBtnLoading')
              return;
            }
             JudgePersonBank(this.agencyId)
              .then((res)=>{
                 if (res.data == null ||  res.data == '') {
                      this.$message({
                      message: "请编辑单位信息发卡银行",
                      type: "warning",
                      showClose: true,
                      duration: 4000,
                      });
                      return;
                      }
               this.judgePersonBank = res.data;
               const arr=[]
                let cardBank = '';
                 for(let i=0;i< this.judgePersonBank.length;i++){
                     if(this.judgePersonBank[i].salaCardBank == '1'){
                       this.cardBank = '1'
                       arr.push(this.judgePersonBank[i].personName)
                    }
               }
               if(this.cardBank == '1'){
                 this.$message({
                 showClose: true,
                 message:  arr+ ",存在银行信息不匹配人员",
                 type: "warning",
                 duration: 4000,
                 });
                 this.$emit("handleSubmitBtnLoading");
                return;
                }
             
             
            const params = { 'agencyId': this.agencyId, 'menuid': this.menuid }
            submitOne(params).then(res => {
              this.$message({
                message: '送审成功',
                type: 'success',
                showClose: true,
                duration: 4000
              })
              // 刷新数据
              this.getList()
              this.$emit('handleSubmitBtnLoading')
            }).catch(() => {
              this.$emit('handleSubmitBtnLoading')
            })
            });
          }).catch(() => {
            this.$emit('handleSubmitBtnLoading')
          })
        }).catch(() => {
          this.$emit('handleSubmitBtnLoading')
        })
      }).catch(() => {
        this.$emit('handleSubmitBtnLoading')
      })
      // }).catch(() => {
      //   this.$emit('handleSubmitBtnLoading')
      // })
      
    },

    // 撤销送审
    handleRejectSubmit() {
      if (this.total === 0) {
        this.$message({
          message: '没有可撤销送审的数据',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        this.$emit('handleRejectSubmitBtnLoading')
        return
      }
      this.queryAgencyNameAndState()
        .then(() => {
          // 审核后不可撤销送审
          if (this.salaryVerifiedInAgencyCode === '1') {
            this.$message({
              message: '当前单位数据已审核，不可撤销送审！',
              type: 'warning',
              showClose: true,
              duration: 4000
            })
            this.$emit('handleRejectSubmitBtnLoading')
            return
          }
          // this.$confirm('确定撤销送审吗？', '提示', {
          //   closeOnClickModal: false,
          //   confirmButtonText: '确定',
          //   cancelButtonText: '取消',
          //   type: 'warning'
          // })
          //   .then(() => {
          const params = { 'agencyId': this.agencyId, 'menuid': this.menuid }
          rejectSubmitOne(params)
            .then(res => {
              this.$message({
                message: '撤销送审成功',
                type: 'success',
                showClose: true,
                duration: 4000
              })
              // 刷新数据
              this.getList()
              this.$emit('handleRejectSubmitBtnLoading')
            })
            .catch(() => {
              this.$emit('handleRejectSubmitBtnLoading')
            })
        })
        .catch(() => {
          this.$emit('handleRejectSubmitBtnLoading')
        })
        // })
        // .catch(() => {
        //   this.$emit('handleRejectSubmitBtnLoading')
        // })
    },

    // handleInput(e, row, name) {
    //   const regex = /^\d{0,16}\.?\d{0,2}$/
    //   const value = e.value
    //   if (!regex.test(value)) {
    //     row[name] = this.inputList['id' + row.id + '_' + name]
    //       ? this.inputList['id' + row.id + '_' + name]
    //       : '0.00'
    //   } else {
    //     this.inputList['id' + row.id + '_' + name] = value
    //   }
    // },

    // handleChange(val, row, name) {
    //   const regex = /^((0|[1-9][0-9]{0,17})|([0]\.\d{1,2}|[1-9][0-9]{0,15}\.\d{1,2}))$/
    //   const value = val.value
    //   if (!regex.test(value)) {
    //     row[name] = this.changeList['id' + row.id + '_' + name]
    //       ? this.changeList['id' + row.id + '_' + name]
    //       : '0.00'
    //   } else {
    //     this.changeList['id' + row.id + '_' + name] = value
    //   }
    // },

    // 全选
    handleCheckAll(val) {
      const checked = val.checked
      for (let i = 0; i < this.list.length; i++) {
        this.list[i].check = checked
      }
      this.checkAll = true
      this.indeterminate = false
      this.checkList = []
      if (checked) {
        for (const item of this.list) {
          if (item.check) {
            this.checkList.push(item)
          }
        }
      }
    },

    // 点击多选按钮
    handleCheck() {
      this.checkList = []
      const totalCount = this.list.length - 1
      let isCheckedCount = 0
      this.list.forEach(item => {
        if (item.check) {
          this.checkList.push(item)
          isCheckedCount++
        }
      })
      this.checkAll = totalCount === isCheckedCount
      this.indeterminate = isCheckedCount > 0 && isCheckedCount < totalCount
    },
    // 附件方法
    appendixOpen() {
      const that = this
      const selection = that.checkList
      if (selection.length === 0) {
        that.openenclosure = false
      } else {
        that.openenclosure = true
      }
      if (this.isSubmitInAgency === 1) {//已送审不可编辑
        that.openenclosure = false
      }
       if(selection.length>0){
          const arr=[]
         for(let i=0;i<selection.length;i++){
                arr.push(selection[i].personName)
            }
           this.$confirm("当前操作:"+arr+ ' 提示!', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }).then(() => {
           const idList = []
      selection.forEach(item => {
        idList.push({ id: item.personId })
      })
      that.$refs.enc.appendixOpen(idList, that.openenclosure, undefined, this.agencyId)
         }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消上传'
          });
        });
       }else{
          const idList = []
      selection.forEach(item => {
        idList.push({ id: item.personId })
      })
      that.$refs.enc.appendixOpen(idList, that.openenclosure, undefined, this.agencyId)
       }
    },
    // 查看详情
    viewInfo(currenRow) {
      const personId = currenRow.personId.replace('noRepeat', '')
      this.$refs.personSalaryInfo.viewInfo(personId, undefined, this.agencyId)
    },
    // 导出
    outPutFile() {
      Object.assign(this.listQuery, this.formData)
      this.listQuery['agencyId'] = this.agencyId
      outPutSalaryReportList(this.listQuery).then(response => {
        const link = document.createElement('a')
        const objectUrl = URL.createObjectURL(response)
        link.href = objectUrl
        link.download = '单位工资编报.xls'
        link.click()
        URL.revokeObjectURL(objectUrl)
      })
    },
    // 上传文件
    uploadExcel(item) {
       this.importLoading=true
      const fileObj = item.file;
      // FormData 对象
      const form = new FormData()
      // 文件对象
     
      form.append("file", fileObj)
      form.append("agencyId", this.agencyId)
      ImportAsync(form)
        .then((response) => {
          this.dialogImportFormVisible = false
          this.importGuid=response.data.guid
          this.Executing=response.data.Executing
          this.uploadLoadImportVisible = true
           this.importLoading=false
        })
    },
    // 导入
    importFile() {
      if (this.isSubmitInAgency === 1) {
        this.$message({
          message: '当前单位数据已送审，不可导入！',
          type: 'warning',
          showClose: true,
          duration: 4000
        })
        return
      }
      this.dialogImportFormVisible = true
    },
    nextInput(event) {
      const vElem = event.target
      const inputArray = document.getElementsByClassName('vxe-input--inner')
      for (let index = 0; index < inputArray.length; index++) {
        if (vElem === inputArray[index]) {
          inputArray[index + 1].focus()
          return
        }
      }
    },
    meanNum (list, field) {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
      })
       return count / list.length
    },
    sumNum (list, field) {
      let count = 0
      list.forEach(item => {
        count += Number(item[field])
        })
      return count
    },
    footerMethod ({ columns, data }) {
      
      const sums = []
      columns.forEach((column, columnIndex) => {
        if (columnIndex === 0) {
          sums.push('合计')
        } else {
          let sumCell = null
          if (columnIndex>4) {
             sumCell = this.sumNum(data, column.property)
            sumCell = Number(sumCell).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
          }else{
            sumCell=''
          }
          sums.push(sumCell)
        }
      })
              // 返回一个二维数组的表尾合计
      return [sums]
   }
  }
}
</script>
<style lang="scss" scoped>
  .file-logo {
    color: #0b68ea;
    font-weight: 900;
    font-size: 18px;
  }
  .warn-font-color {
    color: red;
  }

  .el-table {
    .cell {
      .el-table__expand-icon {
        display: none;
      }

      .el-table__indent {
        padding-left: 0 !important;
      }

      .el-table__placeholder {
        display: none;
      }
    }
  }

  /** 文本框高度 **/
  .el-input:not(.el-pagination__editor):not(.el-input--mini) {
    width: 130px;
    height: 40px !important;
  }

  // 表格小三角
  // ::v-deep.el-table .el-table__expand-icon {
  //   display: inline-block;
  //   width: 20px;
  //   line-height: 20px;
  //   height: 20px;
  //   text-align: center;
  //   margin-right: 3px;
  //   display: none;
  // }

  //::v-deep深度作用选择器混用本地和全局样式
  ::v-deep.el-input:not(.el-pagination__editor):not(.el-input--mini)
  .el-input__inner {
    height: 35px;
    text-align: right !important;
  }
</style>
